import axios, { InternalAxiosRequestConfig, AxiosResponse, AxiosError } from '@ohos/axios'
import { promptAction } from '@kit.ArkUI'

const request = axios.create({
  baseURL: 'http://192.168.101.66:6060',
  timeout: 10000
})

request.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    return config
  },
)

request.interceptors.response.use(
  (response: AxiosResponse) => {
    const { data, code } = response.data
    if (code === 200) {
      return data
    }

    promptAction.showToast(data?.message)
    return Promise.reject(data.message)
  },
  (error) => {
    console.log(`--->${error}`)
    // 错误提示
    promptAction.showToast(error.message)
    return Promise.reject(error.message)
  }
)

export default class Http {
  get<T>(url: string, params?: object) {
    return request.get<any, T>(url, {
      params
    })
  }

  post<T>(url: string, data?: object) {
    return request.post<any, T>(url, {
      data
    })
  }

  put<T>(url: string, data?: object) {
    return request.put<any, T>(url, {
      data
    })
  }

  delete<T>(url: string, params?: object) {
    return request.delete<any, T>(url, {
      params
    })
  }
}